package com.example.juc.big_talk_concurrent.chapter2.article2;

public class Test {

    // 普通同步方法
    public synchronized void test1() {
        System.out.println("1");
    }

    // 静态同步方法
    public static synchronized void test2() {
        System.out.println("2");
    }

    // 同步方法块
    static final Object room = new Object(); // 声明一个锁
    public void test3(){
        synchronized (room) { // 锁住 room 对象
            System.out.println("3");
        }
    }

    public static void main(String[] args) throws InterruptedException {
        Test test = new Test();
        // 实例方法
        test.test1();
        test.test3();
        // 类方法
        Test.test2();

        Thread t1 = new Thread(new MyRunnable(test), "t1");
        t1.start();

        Thread t2 = new Thread(new MyRunnable(test), "t2");
        t2.start();

        t1.join();
        t2.join();

        System.out.println("执行结束");
    }

    static class MyRunnable implements Runnable{

        private final Test test;

        public MyRunnable(Test test) {
            this.test = test;
        }

        @Override
        public void run() {
            // 实例方法
            test.test1();
            test.test3();
            // 类方法
            Test.test2();
        }
    }
}
